Magic Methods (Dunder Methods)
Magic methods, also known as "dunder" (double underscore) methods, are special methods that start and end with double underscores. They allow you to define the behavior of your objects for built-in Python operations.
Common Dunder Methods
__init__(self): Initializes a new object.__str__(self): Returns an informal, readable string representation of the object (used byprint()andstr()).__repr__(self): Returns an official string representation of the object, ideally one that could be used to recreate the object (used byrepr()).__add__(self, other): Defines behavior for the+operator.__len__(self): Defines behavior for thelen()function.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __repr__(self):
return f"Vector(x={self.x}, y={self.y})"
def __add__(self, other):
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
return NotImplemented
def __len__(self):
# A simple implementation of length
return 2
v1 = Vector(2, 4)
v2 = Vector(3, 1)
print(v1) # Output: Vector(2, 4) (uses __str__)
print(repr(v1)) # Output: Vector(x=2, y=4) (uses __repr__)
v3 = v1 + v2 # Uses __add__
print(v3) # Output: Vector(5, 5)